document.addEventListener('DOMContentLoaded', () => {
    // 游戏配置
    const config = {
        gridSize: 6, // 6x6的网格
        tileTypes: 6, // 6种不同类型的方块
        gameTime: 60, // 游戏时间（秒）
        targetScore: 1000, // 目标分数
        basePoints: 10, // 基础得分
        comboMultiplier: 1.5 // 连击乘数
    };

    // 游戏状态
    let gameState = {
        grid: [],
        score: 0,
        timeRemaining: config.gameTime,
        isPlaying: false,
        isSwapping: false,
        firstSelected: null,
        timerInterval: null,
        comboCount: 0
    };

    // 方块类型和颜色
    const tileColors = [
        'tile1', // 红色
        'tile2', // 橙色
        'tile3', // 绿色
        'tile4', // 蓝色
        'tile5', // 紫色
        'tile6' // 粉色
    ];

    const tileIcons = [
        'fa-heart',
        'fa-star',
        'fa-diamond',
        'fa-bell',
        'fa-coffee',
        'fa-anchor'
    ];

    // 获取DOM元素
    const gameBoard = document.getElementById('gameBoard');
    const scoreDisplay = document.getElementById('score');
    const timerDisplay = document.getElementById('timer');
    const targetDisplay = document.getElementById('target');
    const restartBtn = document.getElementById('restartBtn');
    const gameOverModal = document.getElementById('gameOverModal');
    const finalScoreDisplay = document.getElementById('finalScore');
    const gameOverTitle = document.getElementById('gameOverTitle');
    const successMessage = document.getElementById('successMessage');
    const failMessage = document.getElementById('failMessage');
    const playAgainBtn = document.getElementById('playAgainBtn');

    // 初始化游戏
    function initGame() {
        // 重置游戏状态
        gameState = {
            grid: createGrid(),
            score: 0,
            timeRemaining: config.gameTime,
            isPlaying: true,
            isSwapping: false,
            firstSelected: null,
            timerInterval: null,
            comboCount: 0
        };

        // 更新UI
        updateScore();
        updateTimer();
        targetDisplay.textContent = config.targetScore;
        renderGrid();

        // 启动计时器
        if (gameState.timerInterval) clearInterval(gameState.timerInterval);
        gameState.timerInterval = setInterval(updateTimer, 1000);

        // 隐藏游戏结束弹窗
        gameOverModal.classList.add('hidden');
    }

    // 创建初始网格
    function createGrid() {
        const grid = [];

        // 初始化网格
        for (let row = 0; row < config.gridSize; row++) {
            grid[row] = [];
            for (let col = 0; col < config.gridSize; col++) {
                // 确保不会在初始化时就有匹配的三个
                let tileType;
                do {
                    tileType = Math.floor(Math.random() * config.tileTypes);
                } while (
                    (row >= 2 &&
                        grid[row - 1][col] === tileType &&
                        grid[row - 2][col] === tileType) ||
                    (col >= 2 &&
                        grid[row][col - 1] === tileType &&
                        grid[row][col - 2] === tileType)
                );

                grid[row][col] = tileType;
            }
        }

        return grid;
    }

    // 渲染网格
    function renderGrid() {
        gameBoard.innerHTML = '';
        gameBoard.style.gridTemplateColumns = `repeat(${config.gridSize}, 1fr)`;

        for (let row = 0; row < config.gridSize; row++) {
            for (let col = 0; col < config.gridSize; col++) {
                const tile = document.createElement('div');
                const tileType = gameState.grid[row][col];

                // 设置方块样式
                tile.className = `tile aspect-square rounded-lg flex items-center justify-center cursor-pointer transition-all duration-300 ease-in-out ${tileColors[tileType]}`;
                tile.style.animationDelay = `${(row * config.gridSize + col) * 20}ms`;
                tile.style.opacity = '0';
                tile.style.transform = 'scale(0.8)';

                // 添加图标
                const icon = document.createElement('i');
                icon.className = `fa ${tileIcons[tileType]} text-white text-xl md:text-2xl`;
                tile.appendChild(icon);

                // 添加点击事件
                tile.addEventListener('click', () => handleTileClick(row, col));

                // 添加到棋盘
                gameBoard.appendChild(tile);

                // 添加入场动画
                setTimeout(() => {
                    tile.style.opacity = '1';
                    tile.style.transform = 'scale(1)';
                }, 50);
            }
        }
    }

    // 处理方块点击
    function handleTileClick(row, col) {
        if (!gameState.isPlaying || gameState.isSwapping) return;

        const tile = gameBoard.children[row * config.gridSize + col];

        // 如果是第一次选择
        if (gameState.firstSelected === null) {
            gameState.firstSelected = { row, col };
            tile.classList.add('tile-hover');
        }
        // 如果是第二次选择，检查是否相邻
        else {
            const { row: firstRow, col: firstCol } = gameState.firstSelected;

            // 检查是否相邻
            if (
                (Math.abs(firstRow - row) === 1 && firstCol === col) ||
                (Math.abs(firstCol - col) === 1 && firstRow === row)
            ) {
                // 相邻，执行交换
                gameState.isSwapping = true;

                // 取消第一个方块的高亮
                const firstTile = gameBoard.children[firstRow * config.gridSize + firstCol];
                firstTile.classList.remove('tile-hover');

                // 执行交换动画
                swapTilesAnimation(firstRow, firstCol, row, col)
                    .then(() => {
                        // 检查是否有匹配
                        const matches = findMatches();

                        if (matches.length > 0) {
                            // 有匹配，处理匹配
                            processMatches(matches);
                        } else {
                            // 没有匹配，交换回来
                            swapTiles(firstRow, firstCol, row, col);
                            swapTilesAnimation(row, col, firstRow, firstCol)
                                .then(() => {
                                    gameState.isSwapping = false;
                                });
                        }
                    });
            } else {
                // 不相邻，取消第一次选择，选择当前方块
                const firstTile = gameBoard.children[firstRow * config.gridSize + firstCol];
                firstTile.classList.remove('tile-hover');

                gameState.firstSelected = { row, col };
                tile.classList.add('tile-hover');
            }
        }
    }

    // 交换方块位置（数据）
    function swapTiles(row1, col1, row2, col2) {
        const temp = gameState.grid[row1][col1];
        gameState.grid[row1][col1] = gameState.grid[row2][col2];
        gameState.grid[row2][col2] = temp;
    }

    // 交换方块动画
    function swapTilesAnimation(row1, col1, row2, col2) {
        return new Promise(resolve => {
            const tile1 = gameBoard.children[row1 * config.gridSize + col1];
            const tile2 = gameBoard.children[row2 * config.gridSize + col2];

            // 获取两个方块的位置
            const rect1 = tile1.getBoundingClientRect();
            const rect2 = tile2.getBoundingClientRect();

            // 计算移动距离
            const dx = rect2.left - rect1.left;
            const dy = rect2.top - rect1.top;

            // 设置临时定位和移动
            tile1.style.position = 'relative';
            tile1.style.zIndex = '10';
            tile2.style.position = 'relative';
            tile2.style.zIndex = '10';

            // 添加过渡效果
            tile1.style.transition = 'transform 0.3s ease-out';
            tile2.style.transition = 'transform 0.3s ease-out';

            // 执行移动
            tile1.style.transform = `translate(${dx}px, ${dy}px)`;
            tile2.style.transform = `translate(${-dx}px, ${-dy}px)`;

            // 等待动画完成
            setTimeout(() => {
                // 重置样式
                tile1.style.position = '';
                tile1.style.zIndex = '';
                tile2.style.position = '';
                tile2.style.zIndex = '';
                tile1.style.transform = '';
                tile2.style.transform = '';

                // 交换DOM元素位置
                if (row1 !== row2 || col1 !== col2) {
                    const parent = gameBoard;
                    const index1 = row1 * config.gridSize + col1;
                    const index2 = row2 * config.gridSize + col2;

                    if (index1 < index2) {
                        parent.insertBefore(tile2, parent.children[index1]);
                        parent.insertBefore(tile1, parent.children[index2]);
                    } else {
                        parent.insertBefore(tile1, parent.children[index2]);
                        parent.insertBefore(tile2, parent.children[index1]);
                    }
                }

                resolve();
            }, 300);
        });
    }

    // 查找所有匹配
    function findMatches() {
        const matches = [];
        const grid = gameState.grid;

        // 检查水平匹配
        for (let row = 0; row < config.gridSize; row++) {
            for (let col = 0; col < config.gridSize - 2; col++) {
                const currentType = grid[row][col];
                if (currentType !== null &&
                    currentType === grid[row][col + 1] &&
                    currentType === grid[row][col + 2]) {

                    // 找到匹配，检查是否有更多连续的
                    let matchLength = 3;
                    while (col + matchLength < config.gridSize &&
                        grid[row][col + matchLength] === currentType) {
                        matchLength++;
                    }

                    // 添加匹配信息
                    for (let i = 0; i < matchLength; i++) {
                        matches.push({ row, col: col + i, type: currentType });
                    }

                    // 跳过已经匹配的列
                    col += matchLength - 1;
                }
            }
        }

        // 检查垂直匹配
        for (let col = 0; col < config.gridSize; col++) {
            for (let row = 0; row < config.gridSize - 2; row++) {
                const currentType = grid[row][col];
                if (currentType !== null &&
                    currentType === grid[row + 1][col] &&
                    currentType === grid[row + 2][col]) {

                    // 找到匹配，检查是否有更多连续的
                    let matchLength = 3;
                    while (row + matchLength < config.gridSize &&
                        grid[row + matchLength][col] === currentType) {
                        matchLength++;
                    }

                    // 添加匹配信息
                    for (let i = 0; i < matchLength; i++) {
                        matches.push({ row: row + i, col, type: currentType });
                    }

                    // 跳过已经匹配的行
                    row += matchLength - 1;
                }
            }
        }

        // 去重
        return [...new Set(matches.map(match => JSON.stringify(match)))]
            .map(match => JSON.parse(match));
    }

    // 处理匹配
    function processMatches(matches) {
        if (matches.length === 0) {
            gameState.isSwapping = false;
            return;
        }

        // 增加连击计数
        gameState.comboCount++;

        // 计算得分
        const matchCount = matches.length;
        const comboMultiplier = gameState.comboCount > 1 ? gameState.comboCount * config.comboMultiplier : 1;
        const pointsEarned = Math.floor(matchCount * config.basePoints * comboMultiplier);

        // 更新分数
        gameState.score += pointsEarned;
        updateScore();

        // 显示得分动画
        showScorePopup(pointsEarned);

        // 移除匹配的方块
        removeMatches(matches)
            .then(() => {
                // 让方块下落填补空缺
                return letTilesFall();
            })
            .then(() => {
                // 生成新的方块
                return generateNewTiles();
            })
            .then(() => {
                // 检查是否有新的匹配
                const newMatches = findMatches();
                if (newMatches.length > 0) {
                    // 有新的匹配，继续处理
                    processMatches(newMatches);
                } else {
                    // 没有新的匹配，结束交换
                    gameState.comboCount = 0;
                    gameState.isSwapping = false;

                    // 检查游戏是否结束
                    checkGameOver();
                }
            });
    }

    // 移除匹配的方块
    function removeMatches(matches) {
        return new Promise(resolve => {
            // 标记要移除的方块
            const tilesToRemove = new Set();
            matches.forEach(match => {
                tilesToRemove.add(match.row * config.gridSize + match.col);
                gameState.grid[match.row][match.col] = null;
            });

            // 执行移除动画
            const tiles = gameBoard.children;
            tilesToRemove.forEach(index => {
                const tile = tiles[index];
                tile.classList.add('tile-disappear');
                tile.style.opacity = '0';
                tile.style.transform = 'scale(0)';
            });

            setTimeout(resolve, 300);
        });
    }

    // 让方块下落填补空缺
    function letTilesFall() {
        return new Promise(resolve => {
            const grid = gameState.grid;
            let hasFallen = false;

            // 对每一列处理下落
            for (let col = 0; col < config.gridSize; col++) {
                // 从底部向上处理每一行
                for (let row = config.gridSize - 1; row > 0; row--) {
                    // 如果当前位置为空，且上方有方块
                    if (grid[row][col] === null) {
                        // 查找上方最近的非空方块
                        for (let aboveRow = row - 1; aboveRow >= 0; aboveRow--) {
                            if (grid[aboveRow][col] !== null) {
                                // 移动方块下落
                                grid[row][col] = grid[aboveRow][col];
                                grid[aboveRow][col] = null;

                                // 更新DOM显示
                                const tileAbove = gameBoard.children[aboveRow * config.gridSize + col];
                                const tileBelow = gameBoard.children[row * config.gridSize + col];

                                // 交换DOM元素
                                gameBoard.insertBefore(tileAbove, tileBelow);

                                // 添加下落动画
                                tileAbove.style.animation = 'none';
                                tileAbove.offsetHeight; // 触发重绘
                                tileAbove.style.animation = `tileFall 0.3s ease-out forwards`;
                                tileAbove.style.animationDelay = `${row * 30}ms`;

                                hasFallen = true;
                                break;
                            }
                        }
                    }
                }
            }

            // 如果有方块下落，等待动画完成
            if (hasFallen) {
                setTimeout(resolve, 500);
            } else {
                resolve();
            }
        });
    }

    // 生成新的方块
    function generateNewTiles() {
        return new Promise(resolve => {
            const grid = gameState.grid;
            let newTiles = [];

            // 找出所有空位置并生成新方块
            for (let col = 0; col < config.gridSize; col++) {
                for (let row = 0; row < config.gridSize; row++) {
                    if (grid[row][col] === null) {
                        // 生成新方块类型
                        const newType = Math.floor(Math.random() * config.tileTypes);
                        grid[row][col] = newType;

                        // 创建新方块元素
                        const tile = document.createElement('div');
                        tile.className = `tile aspect-square rounded-lg flex items-center justify-center cursor-pointer transition-all duration-300 ease-in-out ${tileColors[newType]} opacity-0 transform scale-0`;

                        // 添加图标
                        const icon = document.createElement('i');
                        icon.className = `fa ${tileIcons[newType]} text-white text-xl md:text-2xl`;
                        tile.appendChild(icon);

                        // 添加点击事件
                        tile.addEventListener('click', () => handleTileClick(row, col));

                        // 添加到棋盘
                        gameBoard.appendChild(tile);
                        newTiles.push(tile);
                    }
                }
            }

            // 为新方块添加出现动画
            newTiles.forEach((tile, index) => {
                setTimeout(() => {
                    tile.style.transition = 'opacity 0.3s ease-out, transform 0.3s ease-out';
                    tile.style.opacity = '1';
                    tile.style.transform = 'scale(1)';
                }, index * 30);
            });

            setTimeout(resolve, newTiles.length * 30 + 300);
        });
    }

    // 显示得分弹出动画
    function showScorePopup(points) {
        const popup = document.createElement('div');
        popup.className = 'fixed top-1/3 left-1/2 transform -translate-x-1/2 bg-primary text-white px-4 py-2 rounded-lg shadow-lg z-30 score-pop';
        popup.textContent = `+${points}`;

        document.body.appendChild(popup);

        setTimeout(() => {
            popup.remove();
        }, 1000);
    }

    // 更新分数显示
    function updateScore() {
        scoreDisplay.textContent = gameState.score;

        // 添加分数变化动画
        scoreDisplay.classList.add('score-pop');
        setTimeout(() => {
            scoreDisplay.classList.remove('score-pop');
        }, 500);

        // 如果达到目标分数，显示成功信息
        if (gameState.score >= config.targetScore) {
            gameState.isPlaying = false;
            clearInterval(gameState.timerInterval);
            showGameOver(true);
        }
    }

    // 更新计时器
    function updateTimer() {
        gameState.timeRemaining--;
        timerDisplay.textContent = gameState.timeRemaining;

        // 添加时间变化动画
        timerDisplay.classList.add('score-pop');
        setTimeout(() => {
            timerDisplay.classList.remove('score-pop');
        }, 500);

        // 时间快用完时显示警告
        if (gameState.timeRemaining <= 10) {
            timerDisplay.classList.add('text-red-500');
            timerDisplay.classList.add('shake');
            setTimeout(() => {
                timerDisplay.classList.remove('shake');
            }, 500);
        }

        // 时间到，游戏结束
        if (gameState.timeRemaining <= 0) {
            gameState.isPlaying = false;
            clearInterval(gameState.timerInterval);
            showGameOver(false);
        }
    }

    // 显示游戏结束弹窗
    function showGameOver(isSuccess) {
        finalScoreDisplay.textContent = gameState.score;

        if (isSuccess) {
            gameOverTitle.textContent = '恭喜你！';
            successMessage.classList.remove('hidden');
            failMessage.classList.add('hidden');
        } else {
            gameOverTitle.textContent = '游戏结束';
            successMessage.classList.add('hidden');
            failMessage.classList.remove('hidden');
        }

        gameOverModal.classList.remove('hidden');
    }

    // 检查游戏是否结束
    function checkGameOver() {
        // 如果分数达到目标，游戏成功结束
        if (gameState.score >= config.targetScore) {
            gameState.isPlaying = false;
            clearInterval(gameState.timerInterval);
            showGameOver(true);
        }
    }

    // 事件监听
    restartBtn.addEventListener('click', initGame);
    playAgainBtn.addEventListener('click', initGame);

    // 初始化游戏
    initGame();

    // 监听窗口大小变化，调整游戏布局
    window.addEventListener('resize', () => {
        // 重新计算游戏棋盘大小
        const gameBoardWrapper = document.querySelector('.game-board-wrapper');
        const availableHeight = gameBoardWrapper.clientHeight;
        const availableWidth = gameBoardWrapper.clientWidth;

        // 设置游戏棋盘的最大尺寸
        const maxDimension = Math.min(availableWidth, availableHeight);
        gameBoard.style.maxWidth = `${maxDimension}px`;
        gameBoard.style.maxHeight = `${maxDimension}px`;
    });

    // 初始调整
    setTimeout(() => {
        window.dispatchEvent(new Event('resize'));
    }, 100);
});